<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-steps :active="active" :finish-status="finishStatus">
        <el-step title="学生申请" description="提交申请，填写补办的原因以及相片"></el-step>
        <el-step title="辅导员审核" :description="changeActive(form.inspectionProgress)"></el-step>
        <el-step title="学工处理"
          :description="`${form.isPay === 0 ? '未缴费：' : '已缴费，备注：'}` + `${$route.query.jwcCmt ? $route.query.jwcCmt : '等待缴费，记录缴费金额'}`"></el-step>
      </el-steps>
    </el-card>
    <el-card class="box-card" style="margin-top: 20px;">
      <div class="titleNav">基本信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <div class="formItem">
          <div>
            <el-form-item label="学号" prop="stuNo">
              <el-input v-model="form.stuNo" placeholder="请输入学号" @blur="changeGet" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <!-- <el-input v-model="form.createTime" placeholder="请输入出生日期" /> -->
              <el-date-picker v-model="form.birthday" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="家庭所在地" prop="hksz2">
              <el-cascader :options="areaOptions" v-model="form.homeLocation" clearable filterable @change="hkszChange" style="width: 100%"></el-cascader>
            </el-form-item>
            <el-form-item label="家庭详细地址" prop="birthplace">
              <el-input v-model="form.birthplace" placeholder="请输入家庭详细地址" />
            </el-form-item>
            <el-form-item label="民族" prop="mz">
              <el-select clearable v-model="form.mz" placeholder="请选择民族" style="width: 100%">
                <el-option v-for="dict in dict.type.rt_nation" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="学生名称" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生名称" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-input v-model="form.gender" placeholder="请输入性别" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-cascader :options="areaOptions" v-model="form.nativePlace" clearable filterable
                @change="addressChange" style="width: 100%"></el-cascader>
                <!-- <el-cascader :options="areaOptions" v-model="form.nativePlace" clearable filterable v-else
                @change="addressChange" style="width: 100%"></el-cascader> -->
            </el-form-item>
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="乘火车区间" prop="railwayStation">
              <el-input v-model="form.railwayStation" placeholder="请输入乘火车区间（南宁到XX站）" />
            </el-form-item>
          </div>
          <!-- <div>
            <el-form-item label="照片" prop="photo">
              <image-upload v-model="form.photo" />
            </el-form-item>
          </div> -->
        </div>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <div class="titleNav">办理信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <div class="formItem">
          <div>
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model="form.gradeName" placeholder="请输入年级" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="班级" prop="className">
              <el-input v-model="form.className" placeholder="请输入班级" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="宿舍楼" prop="dormitoryBuilding">
              <el-input v-model="form.dormitoryBuilding" placeholder="请输入宿舍楼" />
            </el-form-item>
            <el-form-item label="宿舍号" prop="dormitoryNumber">
              <el-input v-model="form.dormitoryNumber" placeholder="请输入宿舍号" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="学院" prop="departmentName">
              <el-input v-model="form.departmentName" placeholder="请输入学院" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="入学时间" prop="enrollmentTime">
              <el-date-picker v-model="form.enrollmentTime" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="申请时间" prop="applyTime">
              <el-date-picker v-model="form.applyTime" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="补办原因" prop="reason">
              <el-input v-model="form.reason" placeholder="请输入补办原因" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="照片" prop="photo">
              <image-upload v-model="form.photo" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>
    <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 20px;">
      <el-button v-if="active === 0" type="primary" @click="submitForm(1)">提交申请</el-button>
      <el-button v-if="finishStatus !== 'success' || form.inspectionProgress === 0" type="primary"
        @click="submitForm(1)">修改提交申请</el-button>
      <el-button type="primary" @click="printing">打印学生证申请表</el-button>
      <!-- <el-button v-if="active === 1 && showRole <= 3" type="primary"
        @click="auditInformation(2, '辅导员')">审核信息</el-button>
      <el-button v-if="active === 2 && showRole <= 2" type="primary" @click="payment(3, '学工')">登记缴费金额</el-button> -->
      <el-button @click="$router.push('/routine/sicr/stuIdReissueLIst')">返 回</el-button>
    </div>
  </div>
</template>

<script>
import { getStuIdReissue, addStuIdReissue, updateStuIdReissue, getStudentInfoByStuId } from "@/api/routine/stuIdReissue";
import { listClass } from "@/api/stuCQS/basedata/class";
import {
  pcaTextArr, // 省市区联动数据，纯汉字
} from 'element-china-area-data'
export default {
  name: "StuIdReissue",
  dicts: ['rt_nation'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // 学生证补办表格数据
      stuIdReissueList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reason: [
          { required: true, message: "补办原因不能为空", trigger: "blur" }
        ],
        inspectionProgress: [
          { required: true, message: "审核状态不能为空", trigger: "blur" }
        ],
        stuNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        stuId: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "学生名称不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        enrollmentTime: [
          { required: true, message: "入学时间不能为空", trigger: "blur" }
        ],
        railwayStation: [
          { required: true, message: "乘火车区间不能为空", trigger: "blur" }
        ],
        birthplace: [
          { required: true, message: "家庭详细地址不能为空", trigger: "blur" }
        ]
      },
      // 申请进展
      active: 0,
      showRole: 0,
      // 查询到的审核信息
      stuMultiLevelReview: {},
      // 审核处理人
      transactor: '',
      // 省市区
      areaOptions: pcaTextArr,
      // 控件禁用
      isDisabled: false,
      // 审核进度状态
      finishStatus: 'success',
      isDisabledStuNo: false
    };
  },
  watch: {
    "$route.query.id": {
      immediate: true,
      handler() {
        this.form = {}
        this.active = 0
        this.finishStatus = 'success'
        if (this.$route.query.id !== undefined) {
          this.handleUpdate()
          if (this.$route.query.inspectionProgress >= 0) {
            this.isDisabled = true
            this.finishStatus = 'success'
          } else if (this.$route.query.inspectionProgress == -1) {
            this.isDisabledStuNo = true
            this.finishStatus = 'error'
          } else {
            this.finishStatus = 'error'
          }
        } else {
          this.reset()
          this.isDisabled = false
          this.isDisabledStuNo = false
          this.finishStatus = 'success'
        }
      }
    }
  },
  created() {
    // this.getList();
    let temp = this.$store.getters.roles;
    temp.map(x => {
      if (x == "admin") {
        this.showRole = 1;
      }

      if (x == "test") { //学工
        this.showRole = 1;
      }

      if (x == "stumanger") { //学务
        this.showRole = 2;
      }

      if (x == "testteacher") { //辅导员
        this.showRole = 3;
      }

      if (x == "teststu") { //学生
        this.showRole = 4;
      }
    });
  },
  methods: {
    // 填写学号时自动获取其他信息
    changeGet() {
      this.form.stuId = this.form.stuNo ? this.form.stuNo : this.$route.query.stuNo
      getStudentInfoByStuId(this.form.stuId).then(response => {
        if (response.data == null) {
          this.$message.error('学号不存在')

          return
        }
        this.form = response.data
        listClass({ // 根据班级名称查询班级信息
          className: this.form.className
        }).then(response => {
          // this.classList = response.rows;
          this.form.counsellorName = response.rows[0].teacher.name
          this.form.counsellorId = response.rows[0].teacher.teacherId
        });
      });
    },
    // 进度变化时改变文字提示
    changeActive(active) {
      if (active === -1) {
        return '申请被驳回，备注：申请不通过，' + this.$route.query.fdyCmt
      } else if (active >= 1) {
        return '申请通过，备注：' + this.$route.query.fdyCmt
      } else {
        return '辅导员审核学生补办请求通不通过'
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuName: null,
        photo: null,
        reason: null,
        stuId: null,
        stuNo: null,
        createTime: null,
        jg: null,
        hksz2: null
      };
      this.active = 0
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      const id = this.$route.query && this.$route.query.id
      getStuIdReissue(id).then(response => {
        this.form = response.data;
        this.form.studentName = this.form.stuName
        // this.form.stuName = this.form.studentName
        if (response.data.inspectionProgress === -1) {
          this.active = 2
        } else {
          this.active = +response.data.inspectionProgress + 1
          // console.log(this.active);
        }
        // 地区转换
        this.form.nativePlace = this.form.jg !== null ? this.parseSelectedPath(this.form.jg) : '暂无填写'
        // 地区转换
        this.form.homeLocation = this.form.hksz2 !== null ? this.parseSelectedPath(this.form.hksz2) : '暂无填写'
      });
    },
    /** 提交按钮 */
    submitForm(active) {
      this.$modal.loading('正在努力加载中，请稍等。。。')
      // 学生提交申请状态
      this.form.inspectionProgress = 0
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStuIdReissue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.active = active
              this.finishStatus = 'success'
              this.isDisabled = true
              // this.$router.replace({ inspectionProgress: this.form.inspectionProgress });
              // 修改成功后修改路上参数
              this.$router.push({ path: this.$route.path, query: { id: this.form.id, stuNo: this.form.stuNo, inspectionProgress: this.form.inspectionProgress } });
              this.$modal.closeLoading()
            });
          } else {
            addStuIdReissue(this.form).then(response => {
              if (response.code === 500) {
                this.$modal.closeLoading()
                return
              }
              else {
                this.$modal.msgSuccess("提交申请成功");
                this.active = active
                // this.reset()
                this.$modal.closeLoading()
              }
            });
          }
        }
      });
    },
    // el-cascader选择处理
    addressChange(arr) {
      this.form.jg = arr[0] + '/' + arr[1] + '/' + arr[2]
    },
    // el-cascader选择处理
    hkszChange(arr) {
      this.form.hksz2 = arr[0] + '/' + arr[1] + '/' + arr[2]
    },
    // 地区回显到el-cascader
    parseSelectedPath(pathString) {
      const pathArray = pathString.split('/');
      // 假设 options 已经被正确设置，并且可以通过遍历找到对应的值
      let currentLevel = this.areaOptions;
      const selectedOptions = [];
      for (let i = 0; i < pathArray.length; i++) {
        const found = currentLevel.find(item => item.label === pathArray[i]);
        if (found) {
          selectedOptions.push(found.value);
          currentLevel = found.children || [];
        } else {
          // 处理未找到的情况，例如返回空数组或显示错误
          break;
        }
      }
      return selectedOptions;
    },
    // 跳转打印页面
    printing() {
      this.$router.push({
        path: '/routine/sicr/studentIdPrinting',
        query: {
          listId: this.form.id || null,
        },
      })
    }
  }
};
</script>

<style scoped>
.titleNav {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0 20px 0;
}

.titleNav::before {
  content: "";
  margin-right: 10px;
  border: 3px solid rgb(64, 158, 255);
}

.formItem {
  display: flex;
}

.formItem>div {
  flex: 1;
}
</style>
